<template>
	<view class="content" @touchmove.stop.prevent="() => {}">
		<div class="my_work_box" id="myworkbox">
			<div class="titlebox">
				<image src="/static/arrow-left.png" style="height: 23px;width: 23px;margin-right: 12px;"
					@click="toback()"></image>
				<text style="color: black;font-size: 20px;font-weight:bold">{{title}}</text>
			</div>
			<scroll-view scroll-y="true" show-scrollbar="false" class="public_box">
				<div class="studyList" v-for="item in downloadList">
					<div style="display: flex; align-items: center;">
						<image v-if="item.type=='pdf'||item.type=='PDF'" src="/static/pdf.png" style="width: 50px;height: 50px;margin-left: 8px;"></image>
						<image v-else-if="item.type=='doc'||item.type=='docx'||item.type=='DOC'||item.type=='DOCX'" src="/static/word.png" style="width: 50px;height: 50px;margin-left: 8px;"></image>
						<image v-else-if="item.type=='xls'||item.type=='xlsx'||item.type=='XLS'||item.type=='XLSX'" src="/static/excel.png" style="width: 50px;height: 50px;margin-left: 8px;"></image>
						<image v-else-if="item.type=='zip'||item.type=='ZIP'" src="/static/zip.png" style="width: 50px;height: 50px;margin-left: 8px;"></image>
						<image v-else-if="item.type=='pptx'||item.type=='ppt'||item.type=='PPT'||item.type=='PPTX'" src="/static/ppt.png" style="width: 50px;height: 50px;margin-left: 8px;"></image>
						<image v-else src="/static/file.png" style="width: 50px;height: 50px;margin-left: 8px;"></image>
						<div style="display: flex;flex-direction: column;border-radius: 16px 0 0 8px;">
							<text style="margin: 0 0 0 10px; font-size: 18px; font-weight: bold;overflow: hidden; text-overflow: ellipsis;white-space: nowrap;max-width: 450rpx;">{{item.name}}</text>
							<text style="margin: 5px 0 0 10px;color: gray;">适用学期：{{item.term}}</text>
							<text style="margin: 5px 0 0 10px;color: gray;">文件来源：{{item.major}}</text>
							<text style="margin: 5px 0 0 10px;color: gray;">文件类型：{{item.type}}</text>
						</div>
					</div>
					<image src="/static/bottom.png" style="width: 25px;height: 25px;margin-right: 13px;"
						@click="download(item)"></image>
				</div>
			</scroll-view>
		</div>
	</view>
</template>

<script>
	import { findLocalPathByItem } from './findMatchingItem.js';
	export default {
		onShareAppMessage() {},
		onShareTimeline() {},
		onLoad(options) {
			this.title = options.title;
			if (this.title == '各类表格') {
				this.getformdownloadList()
			} else if (this.title == '通知文件') {
				this.getnoticedownloadList()
			} else {
				this.getdownloadList()
			}
		},
		data() {
			return {
				title: '',
				downloadList: [],
				localfile:[],
				localpath:'',
				
			}
		},
		created() {
			uni.getStorageInfo({
				success: (res) => {
					if(!res.keys.includes('savefileStorage')){
						console.log('无本地文件')
					}
					else{
						this.localfile=uni.getStorageSync('savefileStorage')
						console.log(this.localfile)
					}
				}
			})
		},
		methods: {
			getdownloadList() {
				uni.request({
					url: 'https://127.0.0.1/data/getdownloadList.php',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						subject: this.title
					},
					success: (res) => {
						this.downloadList = res.data;
					},
					fail: (err) => {
						console.error('请求失败:', err);
						uni.showToast({
							title: '获取数据失败',
							icon: 'none'
						});
					}
				});
			},
			getformdownloadList() {
				uni.request({
					url: 'https://127.0.0.1/data/getformdownloadList.php',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						console.log(res)
						this.downloadList = res.data;
					},
					fail: (err) => {
						console.error('请求失败:', err);
						uni.showToast({
							title: '获取数据失败',
							icon: 'none'
						});
					}
				});
			},
			getnoticedownloadList() {
				uni.request({
					url: 'https://127.0.0.1/data/getnoticedownloadList.php',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						console.log(res)
						this.downloadList = res.data;
					},
					fail: (err) => {
						console.error('请求失败:', err);
						uni.showToast({
							title: '获取数据失败',
							icon: 'none'
						});
					}
				});
			},
			toback() {
				if (getCurrentPages().length > 1) {
					uni.navigateBack({ delta: 1 }); 
				} else {
					uni.redirectTo({
						url: '/pages/index/home'
					});
				}
			},
			download_internet(item){
				uni.showLoading({
					title: '下载中...'
				});
				const fileUrl = `https://127.0.0.1/data/document/${item.download}`;
				console.log(fileUrl)
				const downloadTask = uni.downloadFile({
					url: fileUrl,
					success: (downloadRes) => {
						if (downloadRes.statusCode === 200) {
							console.log('下载成功');
							const fileName = fileUrl.split('/').pop();
							const fileExt = fileName.includes('.') ? fileName.split('.').pop() : '';
							uni.saveFile({
								tempFilePath: downloadRes.tempFilePath,
								filePath: `${uni.env.USER_DATA_PATH}/${fileName}`,
								success: (saveRes) => {
									let savefileinfo={
										"name":item.name,
										"term":item.term,
										"major":item.major,
										"download":item.download,
										"type":item.type,
										"localpath":saveRes.savedFilePath
									}
									this.localfile.unshift(savefileinfo)
									uni.setStorageSync('savefileStorage',this.localfile)
									console.log('文件保存成功');
									uni.openDocument({
										filePath: saveRes.savedFilePath,
										showMenu: true,
										success: () => {
											console.log('打开文档成功');
										},
										fail: (err) => {
											console.error('打开文件失败:', err);
											uni.showToast({
												title: '无法打开文件',
												icon: 'error'
											});
										}
									});
								},
								fail: (err) => {
									console.error('保存文件失败:', err);
									uni.openDocument({
										filePath: downloadRes.tempFilePath,
										showMenu: true,
										success: () => {
											console.log('打开文档成功');
										},
										fail: (err) => {
											console.error('打开文件失败:', err);
											uni.showToast({
												title: '无法打开文件',
												icon: 'error'
											});
										}
									});
								}
							});
						} else {
							console.error('下载失败，状态码:', downloadRes.statusCode);
							uni.showToast({
								title: `下载失败 (${downloadRes.statusCode})`,
								icon: 'error',
								duration: 2000
							});
							this.$emit('download-fail', downloadRes);
						}
					},
					fail: (err) => {
						console.error('下载请求失败:', err);
						if (err.errMsg.includes('url not in domain list')) {
							uni.showToast({
								title: '域名未配置',
								icon: 'error',
								duration: 2000
							});
						} else if (err.errMsg.includes('request:fail')) {
							uni.showToast({
								title: '网络请求失败',
								icon: 'error',
								duration: 2000
							});
						} else {
							uni.showToast({
								title: '下载失败: ' + err.errMsg,
								icon: 'error'
							});
						}
						this.$emit('download-fail', err);
					},
					complete: () => {
						uni.hideLoading();
					}
				});				
				return downloadTask;
			},
			download(item) {
				if(this.localfile==''){
					console.log('无本地文件')
					this.download_internet(item)
				}else{
					this.loalpath=findLocalPathByItem(item, this.localfile);
					console.log(this.localfile)
					uni.openDocument({
						filePath: this.loalpath,
						showMenu: true,
						success: () => {
							console.log('打开本地文档成功');
						},
						fail: (err) => {
							console.error('打开文件失败:', err);
							this.download_internet(item)
						}
					});
				}
			},

		}
	}
</script>

<style>
	.content {
		margin-top: 11%;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: left;
		justify-content: center;
	}

	.titlebox {
		top: 0;
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-left: 15px;
		margin-bottom: 20px;
		letter-spacing: 1px;
	}

	.my_work_box {
		margin: 10px 5px;
		display: flex;
		flex-direction: column;
		align-items: left;
		justify-content: center;
	}

	.public_box {
		height: calc(100vh - 130px);
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		box-sizing: border-box;
		align-items: center;
	}

	.studyList {
		margin-bottom: 20px;
		display: flex;
		flex-direction: row;
		width: 95%;
		height: 140px;
		background-color: white;
		margin-left: 2.5%;
		border-radius: 16px;
		justify-content: space-between;
		align-items: center;
	}
</style>